package collection;

import exception.CollectionEmptyException;

public class FlexibleArrayStack<E> implements IStack<E>{

	private FlexibleArray<E> internalArray = new FlexibleArray<E>();
	private int topIndex = -1;
	
	public FlexibleArrayStack(){}
	
	@Override
	public boolean isEmpty() 
	{
		return this.topIndex == -1;
	}

	@Override
	public int size() 
	{
		return this.topIndex+1;
	}

	@Override
	public void push(E element) 
	{
		this.topIndex += 1;
		this.internalArray.add(element);
	}

	@Override
	public E pop() throws CollectionEmptyException
	{
		if (isEmpty())
		{
			throw new CollectionEmptyException("Stack");
		}
		else
		{
			E retVal = this.internalArray.get(this.topIndex);
			this.internalArray.remove(topIndex);
			this.topIndex -= 1;
			return retVal;
		}
	}

	@Override
	public E top() throws CollectionEmptyException
	{
		if (isEmpty())
		{
			throw new CollectionEmptyException("Stack");
		}
		else
		{
			return this.internalArray.get(this.topIndex);
		}
	}
	
	@Override
	public String toString()
	{
		if (isEmpty())
			return "[]";
		
		String retStr = "[ ";
		for (int i=0; i<=this.topIndex; i++)
		{
			if (i == this.topIndex)
			{
				retStr += this.internalArray.get(i);
			}
			else
			{
				retStr += this.internalArray.get(i) + ", ";
			}
		}
		retStr += " ]";
		
		return retStr;
	}

}
